package org.spring.utils.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JWTUtils {

    // 密钥
   static byte[] key = "1234567890".getBytes();

    public static  String createToken(String username,Integer minute){


        String token = JWT.create()
                .setPayload("username", username)//载荷
                .setExpiresAt(DateUtil.offsetMinute(new Date(),minute))//有效期
                .setKey(key)
                .sign();
        return token;
    }


    /**
     * 校验token 是否正常
     * @param token
     * @return
     */
    public static boolean valid(String token){
        if(StringUtils.hasText(token)) {
           // boolean b =true;// JWT.of(token).setKey(key).verify();//校验token是否有效
            boolean b1 = JWT.of(token).setKey(key).validate(0);//校验token是否过期和是否被篡改
            return b1;
        }
        return false;
    }


    public static  String getUsername(String token){
        JWT jwt = JWT.of(token);
        return jwt.getPayload("username").toString() ;
    }

    /**
     * 获取登录的用户名
     * @return
     */
    public static String getUsername(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)attributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        if(!valid(token))
            return null;
        JWT jwt = JWT.of(token);
        String username = String.valueOf(jwt.getPayload("username"));
        return username;
    }
}
